package com.mine.seckill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@RestController
public class SaleController {
    private static final String COUNT_KEY = "count";
    private static final String LOCK_KEY = "LOCK";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/sale")
    public void sale() throws InterruptedException {
        String clientId = UUID.randomUUID().toString();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        try {
            // 加锁
            stringRedisTemplate.opsForValue().setIfAbsent(LOCK_KEY, clientId, 10, TimeUnit.SECONDS);
            // 续命的timer（可以认为是看门狗）
            scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    // 续命
                    stringRedisTemplate.expire(LOCK_KEY, 10 / 2, TimeUnit.SECONDS);
                }
            }, 10 / 2, 10 / 2, TimeUnit.SECONDS);
            int count = Integer.parseInt(Optional.ofNullable(stringRedisTemplate.opsForValue().get(COUNT_KEY)).orElse("0"));
            if (count > 0) {
                count--;
                // 实现秒杀的业务操作
                Thread.sleep(10);
                stringRedisTemplate.opsForValue().set(COUNT_KEY, String.valueOf(count));
            }
        } finally {
            if (clientId.equals(stringRedisTemplate.opsForValue().get(LOCK_KEY))) {
                // 解锁
                stringRedisTemplate.delete(LOCK_KEY);
            }
            // 删除定时器
            scheduledExecutorService.shutdownNow();
        }
    }

}
